package com.gemini.main.rocketmq;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;

public class AsyncProducer {

    private static int index = 1;

    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException {
        DefaultMQProducer producer = new DefaultMQProducer("qifeizn-rocketmq-test");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();

        producer.setRetryTimesWhenSendAsyncFailed(0);

        for (;;index++) {
            if (index == 55)
                break;
            Message msg = new Message("TopicTest",
                    "TagA",
                    "OrderID188",
                    ("启飞智能"+index).getBytes(RemotingHelper.DEFAULT_CHARSET));

            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.printf("%-10d OK %s %n", index,
                            sendResult.getMsgId());
                }

                @Override
                public void onException(Throwable e) {
                    System.out.printf("%-10d Exception %s %n", index, e);
                    e.printStackTrace();
                }
            });

            Thread.sleep(2000);
        }

        //Shut down once the producer instance is not longer in use.
        producer.shutdown();
    }

}
